package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.common.constants.article.HotArticleConstants;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.dtos.ReadBehaviorDTO;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApReadBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.app.NewBehaviorDTO;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;


@Service
@Slf4j
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {

    @Autowired
    private ApBehaviorEntryService apBehaviorEntryService;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    /**
     * 阅读行为
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult readBehavior(ReadBehaviorDTO dto) {
        //1. 校验参数 文章id必须传

        //2. 根据登录用户id 或 设备id查询行为实体数据(阅读操作可不登录)
        //获取用户id  设备id

        Integer equipmentId = dto.getEquipmentId();
        //用户登录
        ApUser user = AppThreadLocalUtils.getUser();
        //用户id登录
        //获取用户行为对象
        ApBehaviorEntry apBehaviorEntry = null;
        if (user == null){
            apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(null, equipmentId);
        }else {
            apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(),equipmentId);
        }
        if (apBehaviorEntry == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE, "用户未登录也无设备id");
        }
        //3. 判断阅读行为是否存在
        //获取阅读行为
        Query query = Query.query(Criteria.where("entryId").is(apBehaviorEntry.getId())
                .and("articleId").is(dto.getArticleId()));
        ApReadBehavior readBehavior = mongoTemplate.findOne(query, ApReadBehavior.class);

        // 不存在  创建阅读行为 并初始化count字段值为 1
        if (readBehavior == null) {
            ApReadBehavior apReadBehavior = new ApReadBehavior();
            apReadBehavior.setCount((short) 1); //阅读次数
            apReadBehavior.setArticleId(dto.getArticleId());   //文章id
            apReadBehavior.setEntryId(apBehaviorEntry.getId());  //行为对象id
            apReadBehavior.setCreatedTime(new Date());  //登录时间id
            //添加阅读行为
            mongoTemplate.save(apReadBehavior);

            return ResponseResult.okResult(apReadBehavior);
        }
        //4. 存在  将阅读行为的count字段加1 并修改
        short count = (short) (readBehavior.getCount() + 1);
        readBehavior.setCount(count);
        ApReadBehavior ap = mongoTemplate.save(readBehavior);



        //发送消息到队列
        NewBehaviorDTO mess = new NewBehaviorDTO();
        mess.setType(NewBehaviorDTO.BehaviorType.VIEWS);
        mess.setAdd(1);
        mess.setArticleId(dto.getArticleId());
        //发送消息到队列
        rabbitTemplate.convertAndSend(HotArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_QUEUE, JSON.toJSONString(mess));
        log.info("点赞行为 发送消息 ==>{}",JSON.toJSONString(mess));

        return ResponseResult.okResult(ap);
    }
}
